import Taro, { Component } from '@tarojs/taro'
import { View, Text, Picker } from '@tarojs/components'
import { DNavBar, DImagesupload, DAtInpute } from '@/components'
import { AtForm, AtButton, AtIcon, AtActionSheet } from 'taro-ui'
import classNames from 'classnames'
import dayjs from 'dayjs'
import http from '@/api'
import sdk from '@/common/sdk'
import './financingapplication.scss'


export default class FinancingApplicationBox extends Component {

    constructor(props) {
        super(props)
        this.state = {
            moneyform: {},
            list: [],
            id: "",
            startTime: dayjs().format('YYYY-MM-DD'),
            seletOne: {
                defNoop: () => {
                    this.state.seletOne.isOpened = false
                    this.setState({
                        seletOne: { ...this.state.seletOne },
                    })
                }
            }, // 单选对象
            title: '库融申请'
        }
    }

    initSelectOne = ({ title, bind }, sList) => {
        return new Promise((res, rej) => {
            this.setState({
                seletOne: {
                    ...this.state.seletOne,
                    isOpened: true,
                    title,
                    sList: sList.filter(item => (item.status = this.state.moneyform[bind] === item.text, true)), // 反显高亮值
                    selectListItem: (item) => {
                        item.status = !item.status
                        if (item.status) {
                            this.state.seletOne.value = item
                            res.call(this, item)
                        }
                        this.state.seletOne.isOpened = false
                        this.setState({
                            seletOne: { ...this.state.seletOne },
                        })
                    }
                }
            })
        })
    }

    componentWillMount() {
        let { id = '' } = this.$router.params
        if (id) {
            this.setState({
                id
            })
            this.getFormData(id)
        }
    }

    getFormData(id) {
        http.getFormInfo(id).then(res => {

        })
    }

    componentDidShow() {
        this.getCarInfo()
        sdk.setTitleInfo(this.state.title)
    }

    getCarInfo() {
        let _carList = sessionStorage.getItem('_carList')
        if (!_carList) {
            return
        }
        let _obj = JSON.parse(_carList), _arr = []
        if (this.state.moneyform.carList && this.state.moneyform.carList.length > 0) {
            _arr = [...this.state.moneyform.carList]
        }
        _arr.push(_obj)
        this.setState({
            moneyform: {
                ...this.state.moneyform,
                carList: _arr
            }
        }, () => {
            sessionStorage.removeItem('_carList')
            this.bindCarform('amFinnanceMoney', this.state.moneyform.carList.length * 175)
            this.bindCarform('amTotalCarCount', this.state.moneyform.carList.length)
        })
    }

    addCarInfo() {
        let { moneyform } = this.state
        if (moneyform.carList && moneyform.carList.length >= 5) {
            return Taro.showToast({
                title: '最多添加5台车辆!',
                icon: "none"
            })
        }
        Taro.navigateTo({
            url: '/pages/addfinancingcar/addfinancingcar'
        })
    }


    onHandleImage = () => {
        Taro.navigateTo({
            url: '/pages/itemImages/itemImages?status=paypath'
        })
    }

    submitHandle = () => {
        let { id, moneyform } = this.state
        let _obj = ['amSpendPeriod', 'amSpendDate', 'carList', 'amMonitorType', 'amMonitorAddr', 'imageUrl', 'amTotalCarCount', 'amFinnanceMoney']
        let _objtext = {
            amSpendPeriod: '请选择用款天数',
            amSpendDate: '请选择用款日期',
            carList: '请选择库融车辆',
            amMonitorType: '请选择监管方式',
            amMonitorAddr: '请选择监管地址',
            imageUrl: '请上传付款路径'
        }
        let _status = false, _item = ''
        for (let i = 0, j = _obj.length; i < j; i++) {
            if (!moneyform[_obj[i]]) {
                _status = true
                _item = _objtext[_obj[i]]
                break
            }
        }
        // _obj.map(item => {
        //     if (!moneyform[item]) {
        //         _status = true
        //     }
        // })
        if (moneyform.carList && moneyform.carList.length === 0) {
            _status = true
            _item = '请选择库融车辆'
        }
        if (_status) {
            return Taro.showToast({
                title: _item,
                icon: "none"
            })
        }
        let appStorageApplyVO = Object.assign(moneyform, { id })

        http.saveFormInfor(appStorageApplyVO).then(() => {
            Taro.showToast({
                title: '已提交库融申请!',
                duration: 800,
                mask: true
            }).then(() => {
                setTimeout(() => {
                    // Taro.navigateBack({
                    //     delta: 1
                    // })
                    Taro.redirectTo({
                        url: `/pages/financingorder/financingorder?active=${0}`
                    })
                }, 1000);
            })
        })
    }
    bindCarform = (key, value) => {
        if (key) {
            this.setState({
                moneyform: Object.assign(this.state.moneyform, { [key]: value })
            })
        }
    }
    onChangeTime(e) {
        let { value } = e.detail
        let _value = dayjs(value).format('YYYY-MM-DD')
        this.bindCarform('amSpendDate', _value)
    }

    onCancel(i) {
        let { moneyform } = this.state
        moneyform.carList.splice(i, 1)
        this.setState({
            moneyform
        }, () => {
            this.bindCarform('amFinnanceMoney', this.state.moneyform.carList.length * 175)
            this.bindCarform('amTotalCarCount', this.state.moneyform.carList.length)
        })
    }

    selectCarSource = (props) => {
        this.initSelectOne(props, [
            { text: '车辆监管' },
            { text: '证件监管' }
        ]).then(selectItem => {
            this.bindCarform(props.bind, selectItem.text)
        })
    }
    selectAddreSource = (props) => {
        this.initSelectOne(props, [
            { text: '广东省广州市天河区利通大厦1号' },
            { text: '广东省广州市员村一横路1号' }
        ]).then(selectItem => {
            this.bindCarform(props.bind, selectItem.text)
        })
    }



    selectDate = (props) => {
        this.initSelectOne(props, [
            { text: '3' },
            { text: '7' },
            { text: '15' },
            { text: '30' }
        ]).then(selectItem => {
            this.bindCarform(props.bind, selectItem.text)
        })
    }
    render() {
        const {
            moneyform,
            list,
            startTime,
            seletOne,
            title
        } = this.state
        const _bindCarform = function (value) {
            this.bindCarform(arguments[arguments.length - 1].bind, value)
        }
        const _imageList = function (key, value) {
            let _imageUrl = value[0].url
            this.bindCarform(key, _imageUrl)
        }
        const itemImagesHtml1 =
            <View className='b_financingapplication__images_enterpris'>
                <View className='item_title'>
                    <Text className='item_title__left item_title__require'>付款路径</Text>
                    <Text className='item_title__right' onClick={this.onHandleImage.bind(this)}>查看范例</Text>
                </View>
                <DImagesupload count={1} value={moneyform.imageUrl} bind='imageUrl' onChangeImages={_imageList.bind(this, 'imageUrl')}></DImagesupload>
            </View>
        return (
            <View className='b_financingapplication'>
                <DNavBar title={title}></DNavBar>
                <View className='b_financingapplication__box'>
                    <View className='b_financingapplication__form '>
                        <AtForm>
                            {/* <DAtInpute type='number' value={moneyform.amSpendPeriod} bind="amSpendPeriod" onChange={_bindCarform.bind(this)} title='用款天数' placeholder='请选择用款天数'></DAtInpute> */}
                            <DAtInpute value={moneyform.amSpendPeriod ? moneyform.amSpendPeriod + '天' : moneyform.amSpendPeriod} bind='amSpendPeriod' require={true} onChange={_bindCarform.bind(this)} title='用款天数' icon='chevron-right' placeholder='请选择用款天数' onRightHanlde={this.selectDate}></DAtInpute>
                            <Picker mode='date' value={'YYYY-MM-DD'} start={startTime} onChange={this.onChangeTime.bind(this)}>
                                <View className='b_financin__time'>
                                    <View className='b_financin__time_text item_title__require'>用款日期</View>
                                    <View className='b_financin__time_value'>
                                        <View className={classNames('b_financin__time_value__item', moneyform.amSpendDate ? 'b_financin__time_active' : '')}>{moneyform.amSpendDate || '请选择用款日期'}</View>
                                        <AtIcon value='chevron-right' color='#ccc' size='24'></AtIcon>
                                    </View>
                                </View>
                            </Picker>
                            <View className='b_financingapplication__item'>
                                <View className='b_financingapplication__item_title item_title__require'>库融车辆</View>
                                <View className='b_financingapplication__item_right' onClick={this.addCarInfo.bind(this)}>
                                    <View className={'b_financingapplication__item_value'}>请填写车辆信息</View>
                                    <AtIcon value='add-circle' color='#ccc' size='24'></AtIcon>
                                </View>
                            </View>
                            {
                                moneyform.carList && moneyform.carList.length > 0 && <View className='b_financingapplication__list'>
                                    {
                                        moneyform.carList && moneyform.carList.map((item, i) => {
                                            return <View className='b_financingapplication__list_item'>
                                                <View className='b_financingapplication__list_title'>{item.adCarType}</View>
                                                <AtIcon value='subtract-circle' color='#ccc' size='24' onClick={this.onCancel.bind(this, i)}></AtIcon>
                                            </View>
                                        })
                                    }
                                </View>
                            }

                            <DAtInpute require onChange={_bindCarform.bind(this)} bind='amMonitorType' value={moneyform.amMonitorType} title='监管方式' icon='chevron-right' placeholder='请选择监管方式' onRightHanlde={this.selectCarSource}></DAtInpute>
                            <DAtInpute require onChange={_bindCarform.bind(this)} bind='amMonitorAddr' value={moneyform.amMonitorAddr} title='监管地址' icon='chevron-right' placeholder='请选择监管地址' onRightHanlde={this.selectAddreSource}></DAtInpute>
                        </AtForm>
                    </View>
                    <View className='b_financingapplication__images'>
                        {itemImagesHtml1}
                    </View>
                    <View className='b_financingapplication__images_enterpris'>
                        <View className='item_title'>
                            <View className='item_title__left'>
                                <Text className='item_title__left_carnum'>合计车辆数：</Text>
                                {
                                    moneyform.amTotalCarCount && <Text className='item_title__left_num'>共{moneyform.amTotalCarCount}台</Text>
                                }
                            </View>
                            <View className='item_title__left'>
                                <Text className='item_title__right_cost'>库融总额</Text>
                                <Text className='item_title__right_money'>￥{window.toFixed(moneyform.amFinnanceMoney) || 'xxx'}万元</Text>
                            </View>
                        </View>
                        <View>

                        </View>
                    </View>
                    <View className='b_financingapplication__footer'>
                        <AtButton className='item_btn' onClick={this.submitHandle.bind(this)}>提交申请</AtButton>
                    </View>
                </View>

                <View>
                    <AtActionSheet className="at-select-one" isOpened={seletOne.isOpened} onClose={seletOne.onClose || seletOne.defNoop}>
                        <View className='at-select-one__title'>
                            <View className='at-select-one__title_cancel' onClick={seletOne.cancel || seletOne.defNoop}>{seletOne.cancelText || '取消'}</View>
                            <View className='at-select-one__title_item'>{seletOne.title}</View>
                            <View className='at-select-one__title_submit' onClick={seletOne.commit || seletOne.defNoop}>{seletOne.commitText || '提交'}</View>
                        </View>
                        <View className='at-select-one__type'>
                            {
                                seletOne.sList && seletOne.sList.map((item, i) => {
                                    return <View onClick={seletOne.selectListItem.bind(this, item)} className={classNames('at-select-one__type_item', item.status ? 'at-select-one__active' : '')} key={i}>{item.text}</View>
                                })
                            }
                        </View>
                    </AtActionSheet>
                </View>
            </View>
        )
    }
}